package com.foo.DAO;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;

import javax.sql.DataSource;

import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import com.foo.Entity.HistoricalData;
import com.foo.Entity.RealTimeData;


public class RealtimeDAOImpl implements RealtimeDAO 
{
	private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
    MapSqlParameterSource namedParameters =null;
    MapSqlParameterSource namedParameters1 =null;
    String query = "";
    String updatequery = "";
	 String ticker = "";
	 int size=0;
	
	 public void setDataSource(DataSource dataSource) {
		    this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
		}
	 
	@Override
	public String selectForum(String param, Timestamp timestamp) 
	{
		try
		{
		 query = "select r.Id,r.ticker_symbol,r.open_value,d.company,d.sector_name,d.industry,d.country,d.state,d.market_cap from tickerinfo d " +
		 		"join realtimestockdata r on d.ticker_symbol=r.ticker_symbol where d.ticker_symbol=:ticker_symbol order by r.currentdate LIMIT 0,1";
		
		 namedParameters = new MapSqlParameterSource();
		 namedParameters.addValue("ticker_symbol", param);
		 final String tickersym = param;
		 final Timestamp ts=timestamp;
		 return (String) namedParameterJdbcTemplate.queryForObject(query,
					namedParameters, new RowMapper() 
			{
				public Object mapRow(ResultSet resultSet, int rowNum)
						throws SQLException {
						int j=0;
						//resultSet.setFetchSize(25);
						if (resultSet !=null)
						{
							resultSet.last();
							size=resultSet.getRow();
							resultSet.beforeFirst();
							
						}
						while(resultSet.next())
						{
							updatequery ="UPDATE realtimestockdata SET currentdate =:currentdate where ticker_symbol=:ticker_symbol and id=:id";
							namedParameters1=new MapSqlParameterSource();
							namedParameters1.addValue("ticker_symbol", tickersym);
							namedParameters1.addValue("currentdate", ts);
							namedParameters1.addValue("id", resultSet.getInt(1));
							int success= namedParameterJdbcTemplate.update(updatequery, namedParameters1);	
							if(success == 1)
							{
								System.out.println("Update Success");
							}
							
							ticker += resultSet.getString(2) + ',' +resultSet.getDouble(3)+',' +ts+ ',' + resultSet.getString(4) 
							+ ',' + resultSet.getString(5) + ',' + resultSet.getString(6) + ',' + resultSet.getString(7) + ',' + resultSet.getString(8) 
							+ ',' + resultSet.getDouble(9) + ',';
						}
					return ticker.toString(); 
				}
			});
		}
		catch(EmptyResultDataAccessException e)
		{
			return null;
		}
	}

}
